package com.guangzhoujiayou.bean;

import cn.hutool.crypto.SecureUtil;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.guangzhoujiayou.utils.GsonUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;

/**
 * 请求体
 */
@Data
@Slf4j
public class ReqBody implements Serializable {
    private static final long serialVersionUID = -6523649563611273615L;

    //客户端
    private String clientId = "";
    //秘钥
    private String secret = "";
    //签名
    private String sign = "";
    // 1621143114 单位秒
    private long timestamp;
    //用户IP地址
    private String ip;
    //token
    private String token;
    //请求参数数据
    private Object data;

    //生成签名
    private String createSign() {
        String dataStr = "";
        if (null != data) {
            dataStr = GsonUtil.toJson(data);
        }
        String s = clientId + String.valueOf(timestamp) + secret + dataStr;
        log.info("createSign,before:" + s);
        String signStr = SecureUtil.md5().digestHex16(s);
        log.info("createSign,after:" + signStr);
        log.info("signVerification:" + sign.equals(signStr));
        return signStr;
    }

    //签名校验,true 合法 false 不合法
    public boolean signVerification() {
        return sign.equals(createSign());
    }

    public <T> T getData(Class<T> clazz) {
        if (null == data) {
            return null;
        }
        String dataStr = GsonUtil.toJson(data);
        return GsonUtil.fromJson(dataStr, clazz);
    }

    public <T> T getParam(String key, Class<T> clazz) {
        if (null == data) {
            return null;
        }
        JsonElement element = null;
        JsonElement jsonElement = GsonUtil.toJsonTree(data);
        if (jsonElement.isJsonObject()) {
            JsonObject asJsonObject = jsonElement.getAsJsonObject();
            element = asJsonObject.get(key);
        }
        if (null == element) {
            return null;
        }
        return GsonUtil.fromJson(element, clazz);
    }

    public String getParamStr(String key) {
        return this.getParam(key, String.class);
    }
}
